package com.n9.util;

import java.net.InetAddress;
import java.net.NetworkInterface;

/**
 * 网络工具包
 * @author ice
 * @since 2019/1/16 14:02
 */
public final class NetUtils {

    /**
     * 获取本机网卡的mac地址
     * @return
     */
    public static final String getMacAddress() {
        try {
            InetAddress ia = InetAddress.getLocalHost();
            byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();

            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < mac.length; i++) {
                if (i != 0) {
                    sb.append("-");
                }
                // mac[i] & 0xFF 是为了把byte转化为正整数
                sb.append(String.format("%02x", Integer.valueOf(mac[i] & 0xFF)));
            }

            // 把字符串所有小写字母改为大写成为正规的mac地址并返回
            return sb.toString().toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
